﻿using BusinessLayer;
using BusinessLayer.VDataEntities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Http;
using TrialManagementTool.App_Start;
using TrialManagementTool.Helper;
using TrialManagementTool.Models;
using TrialManagmentTool.Helper;
using TrialManagmentTool.Models;

namespace TrialManagementTool.Controllers.API
{
    [WebApiExceptionFilter]
    [APIAuthorize]
    public class TrialController : ApiController
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="provinceid"></param>
        /// <param name="product"></param>
        /// <param name="crop"></param>
        /// <param name="statuscode">0:尚未开始,1:正在进行,2:已提交,3:已完成</param>
        /// <param name="_search"></param>
        /// <param name="nd"></param>
        /// <param name="rows"></param>
        /// <param name="page"></param>
        /// <param name="sidx"></param>
        /// <param name="sord"></param>
        /// <returns></returns>

        public VTrial[] GetTrialWorkByCondition(string provinceid, int? product, int? crop, int? productCategory, int? statuscode, string _search, string nd, int rows, int page, string sidx, string sord)
        {
            TrialSiteStatus status = TrialSiteStatus.Working;
            List<long> longprovinces = new List<long>();
            if (!string.IsNullOrEmpty(provinceid))
            {
                string[] strpro = provinceid.Split(',').ToArray();
                foreach (string spro in strpro)
                {
                    if (!string.IsNullOrEmpty(spro))
                    {
                        longprovinces.Add(long.Parse(spro));
                    }
                }
            }

            if (statuscode == 0)
            {
                List<VTrial> temp = new List<VTrial>();
                //temp = TrialBusiness.GetTrialList(crop, product, longprovinces.ToArray(), status).ToList();
                status = TrialSiteStatus.New;
                temp.InsertRange(0, TrialBusiness.GetTrialList(crop, product, productCategory, longprovinces.ToArray(), status).ToList());
                return temp.ToArray();
            }
            else if (statuscode == 1)
            {
                status = TrialSiteStatus.Working;
                return TrialBusiness.GetTrialList(crop, product, productCategory, longprovinces.ToArray(), status);
            }
            else if (statuscode == 2)
            {
                status = TrialSiteStatus.Submitted;
                return TrialBusiness.GetTrialList(crop, product, productCategory, longprovinces.ToArray(), status);
            }
            else if (statuscode == 3)
            {
                status = TrialSiteStatus.Completed;
                return TrialBusiness.GetTrialList(crop, product, productCategory, longprovinces.ToArray(), status);
            }
            else
            {
                return TrialBusiness.GetTrialList(crop, product, productCategory, longprovinces.ToArray(), status);
            }

        }

        public void UpdateAdminInfo(TrialInfo trialInfo)
        {
            TrialBusiness.UpdateAdminInfo(trialInfo.TrialID, trialInfo.TTMID, trialInfo.FSM, trialInfo.CA, trialInfo.ProjectCategoryID);
        }

        public ResponseMessage AssignTask(TrialAssaginModel model)
        {
            ResponseMessage responseMessage = new ResponseMessage();
            try
            {
                List<VTrialCandidate> trialList = new List<VTrialCandidate>();
                string userid = "";
                foreach (PromoterCity item in model.trialCandidateList)
                {
                    VDataEntity assaginCity = new VDataEntity() { ID = item.ProvinceID };
                    VPromoter promoter = new VPromoter() { ID = item.PromoterID };
                    if (string.IsNullOrEmpty(userid))
                    {
                        userid = item.PromoterUserName;
                    }
                    else
                    {
                        userid = string.Format("{0}|{1}", userid, item.PromoterUserName);
                    }
                    trialList.Add(new VTrialCandidate { Province = assaginCity, Promoter = promoter });
                }
                VDataEntity currentUser = UserHelper.GetCurrentAdminUser();
                BusinessLayer.TrialBusiness.AssignTrialTask(model.vTrialGuide, trialList.ToArray(), currentUser.ID, model.projectCategoryID, model.ca, model.fsm);
                //调用微信端的方法
                WeChatHelper helper = new WeChatHelper();
                Wxmessage message = new Wxmessage();
                message.FromUserName = userid;
                message.Content = string.Format("系统信息：你收到{2}新分配的试验 产品:{0} 农作物:{1}，请尽快登录页面完成试验", model.vTrialGuide.ProductName, model.vTrialGuide.CropName, currentUser.Name);
                helper.SendTextMessage(message);
                responseMessage.status = ResponseType.Success.ToString();
            }
            catch (Exception ex)
            {
                responseMessage.status = ResponseType.Fail.ToString();
                LogHelper.Error("AssignTask" + ex);
            }
            return responseMessage;
        }

        public void ReminderTask(VTrialSite trialSite)
        {
            // Step 1根据Trial 获取用户Weixin ID
            VTrialDetail trialDetail = TrialBusiness.GetTrialDetail(trialSite.ID);
            VDataEntity user = UserHelper.GetCurrentAdminUser();
            //调用微信端的方法
            WeChatHelper helper = new WeChatHelper();
            Wxmessage message = new Wxmessage();
            message.FromUserName = trialDetail.PromoterUserName;
            message.Content = string.Format("系统信息：你收到{5}的提醒，你有未完成的试验，省份:{0} 产品:{1} 农作物:{2} 试验点:{3}， <a href='{4}'>点击此处立即查看</a>", trialDetail.Province, trialDetail.Product, trialDetail.Crop, trialDetail.TrialSite.Address, UrlHelper.alterContent("TrialMobile/ReportManagement?id=" + trialSite.ID), user.Name);
            helper.SendTextMessage(message);
        }

        public void ReminderTaskNotStart(VTrial trial)
        {
            // Step 1根据Trial 获取用户Weixin ID
            VTrial trialDetail = TrialBusiness.GetTrialByTrialID(trial.ID);
            VDataEntity user = UserHelper.GetCurrentAdminUser();
            //调用微信端的方法
            WeChatHelper helper = new WeChatHelper();
            Wxmessage message = new Wxmessage();
            message.FromUserName = trialDetail.PromoterUserName;
            message.Content = string.Format("系统信息：你收到{5}的提醒，你有尚未开始的试验，分配时间:{3} 省份:{0} 产品:{1} 农作物:{2}， <a href='{4}'>点击此处立即查看</a>", trialDetail.Province, trialDetail.Product, trialDetail.Crop, trialDetail.CreatedDate.Value.ToString("yyyy-MM-dd"), UrlHelper.alterContent("TrialMobile/TrialManagement"), user.Name);
            helper.SendTextMessage(message);
        }

        public void ApproveTrial(VTrialSite trialSite)
        {
            TrialBusiness.ApproveTrials(trialSite.ID);
            VDataEntity user = UserHelper.GetCurrentAdminUser();
            VTrialDetail detail = TrialBusiness.GetTrialDetail(trialSite.ID);
            //调用微信端的方法
            WeChatHelper helper = new WeChatHelper();
            Wxmessage message = new Wxmessage();
            message.FromUserName = detail.PromoterUserName;
            message.Content = string.Format("系统信息：你的试验产品:{0} 农作物:{1} 试验点:{3} 由{2}审批通过", detail.Product, detail.Crop, user.Name, detail.TrialSite.Address);
            helper.SendTextMessage(message);
        }

        public void DisApproveTrial(VTrialSite trialSite)
        {
            string wechattemplate = "系统信息：你的试验产品:{0} 农作物:{1} 试验点:{2} 由{3}审批拒绝";
            OperateTrialMethod(trialSite, wechattemplate);
        }

        public void RollBackTrial(VTrialSite trialSite)
        {
            string wechattemplate = "系统信息：你的试验产品:{0} 农作物:{1} 试验点:{2} 由{3}审批撤回批准";
            OperateTrialMethod(trialSite, wechattemplate);
        }

        private static void OperateTrialMethod(VTrialSite trialSite, string wechattemplate)
        {
            BusinessLayer.TrialBusiness.DisApproveTrials(trialSite.ID);
            VDataEntity user = UserHelper.GetCurrentAdminUser();
            VTrialDetail detail = TrialBusiness.GetTrialDetail(trialSite.ID);
            //调用微信端的方法
            WeChatHelper helper = new WeChatHelper();
            Wxmessage message = new Wxmessage();
            message.FromUserName = detail.PromoterUserName;
            message.Content = string.Format(wechattemplate, detail.Product, detail.Crop, detail.TrialSite.Address, user.Name);
            helper.SendTextMessage(message);
        }

        [HttpGet]
        public List<TrialViewModel> GetPromoterTrialList(string provinceid, string _search, string nd, int rows, int page, string sidx, string sord)
        {
            List<long> longprovinces = new List<long>();
            if (!string.IsNullOrEmpty(provinceid))
            {
                string[] strpro = provinceid.Split(',').ToArray();

                foreach (string spro in strpro)
                {
                    if (!string.IsNullOrEmpty(spro))
                    {
                        longprovinces.Add(long.Parse(spro));
                    }
                }
            }
            VTrialCandidate[] CandidateList = TrialBusiness.GetTrialCandidateList(longprovinces.ToArray());

            List<TrialViewModel> result = new List<TrialViewModel>();
            for (int i = 0; i < CandidateList.Count(); i++)
            {
                TrialViewModel model = new TrialViewModel();
                model.City = CandidateList[i].Province.Name;
                model.CityID = CandidateList[i].Province.ID;
                model.Promoter = CandidateList[i].Promoter.ChineseName;
                model.PromoterID = CandidateList[i].Promoter.ID;
                model.PromoterUserName = CandidateList[i].Promoter.Name;
                model.ID = i;
                result.Add(model);
            }

            return result;
        }

        public long AddNewTrialByPromoter(TrialBasicInfo data)
        {
            VDataEntity promoterInfo = UserHelper.GetCurrentPromoterUser();
            long trialId = TrialBusiness.CreateTrial(data.trialInfo.cropID, data.trialInfo.cropName, data.trialInfo.productID, data.trialInfo.productName, data.trialInfo.provinceID, promoterInfo.ID);
            return trialId;
        }

        [HttpPost]
        public ResponseMessage UpdateInputs(ReportInputModel model)
        {
            ResponseMessage responseMessage = new ResponseMessage();
            try
            {
                ReportBusiness.UpdateReports(model.reportid, model.comment, model.inputData.ToArray());
                responseMessage.status = ResponseType.Success.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Error("UpdateInputs" + ex);
                responseMessage.status = ResponseType.Fail.ToString();
            }
            return responseMessage;
        }

        public long AddTrialBasicInfo(DynamicMainInfo data)
        {
            return TrialBusiness.FillBasicInfo(data.ID, data.basicInfo);
        }

        public VDataEntity[] GetProjectCategories()
        {
            return TrialBusiness.GetProjectCategories();
        }

        public VTrial[] GetTrialByPromoterID()
        {
            VDataEntity currentUser = UserHelper.GetCurrentPromoterUser();
            return TrialBusiness.GetTrialByPromoterID(currentUser.ID);
        }

        public Dictionary<long, List<VItem>> GetAllFieldsDataSource()
        {
            Dictionary<long, List<VItem>> datasource = ReportBusiness.GetAllFieldsDataSource();
            return datasource;
        }

        public VTrialGuide GetTrialGuide(long ID)
        {
            return TrialBusiness.GetTrialGuide(ID);
        }

        public ResponseMessage SubmitFinalReport(FinalSummarySubmitModel data)
        {
            ResponseMessage responseMessage = new ResponseMessage();
            try
            {
                TrialBusiness.CompleteTrial(data.TrialID, data.LastObserveDate, data.EffectResult, data.EffectDescription, data.IsAcceptable, data.Comments, data.YieldsEffert, data.CropDescription);
                responseMessage.status = ResponseType.Success.ToString();
            }
            catch (Exception ex)
            {
                responseMessage.status = ResponseType.Fail.ToString();
                LogHelper.Error("SubmitFinalReport", ex);
            }
            return responseMessage;
        }

        [HttpGet]
        public List<VReportFieldInfo> CheckTrialMandaryFields(long id)
        {
            List<VReportFieldInfo> tempList = TrialBusiness.CheckTrialMandaryFields(id).ToList();
            Dictionary<long, List<VReportInfo>> tempDict = ReportBusiness.GetAllInputDataFieldByTrialSiteID(id);
            List<VReportInfo> dataList = new List<VReportInfo>();
            long count = 1;
            foreach (var item in tempDict)
            {
                int yongyao = 1, guancha = 1;
                for (int i = 0; i < item.Value.Count(); i++)
                {
                    if (item.Value[i].IsObserveInfo == true)
                    {
                        item.Value[i].ReportName = string.Format("第{0}次调查", Common.ConvertNumToChinese(guancha));
                        guancha++;
                    }
                    else
                    {
                        item.Value[i].ReportName = string.Format("第{0}次用药", Common.ConvertNumToChinese(yongyao));
                        yongyao++;
                    }
                    dataList.Add(new VReportInfo() { ReportName = item.Value[i].ReportName, ID = item.Value[i].ID, sortNumber = count });
                    count++;
                }
            }
            foreach (var temp in tempList)
            {
                VReportInfo compare = dataList.Find(o => o.ID.Equals(temp.ID));
                if (compare != null)
                {
                    temp.ReportName = string.Format("{0}{1}", temp.ReportName, compare.ReportName);
                    temp.ID = compare.sortNumber;
                }
            }
            return tempList.OrderBy(c => c.ID).ToList();
        }

        [HttpPost]
        public void DeleteImage(VImage image)
        {
            ReportBusiness.DeleteImage(image.ID);
        }

        public VTrialSite[] GetAllTrialSite(long id)
        {
            return TrialBusiness.GetTrialSiteByTrialID(id);
        }

        [HttpPost]
        public long CreateNewProcess(VDataEntity data)
        {
            return ReportBusiness.CreateNewProcess(data);
        }

        public List<VReportInfo> GetProcessInfoByProcessID(long id)
        {
            List<VReportInfo> observerData, nonObserverData = new List<VReportInfo>();
            observerData = ReportBusiness.GetProcessInfoByProcessID(id, true).ToList();
            nonObserverData = ReportBusiness.GetProcessInfoByProcessID(id, false).ToList();
            for (int i = 0; i < observerData.Count(); i++)
            {
                observerData[i].ReportName = string.Format("第{0}次调查", Common.ConvertNumToChinese(i + 1));
            }
            for (int i = 0; i < nonObserverData.Count(); i++)
            {
                nonObserverData[i].ReportName = string.Format("第{0}次用药", Common.ConvertNumToChinese(i + 1));
            }
            observerData.InsertRange(0, nonObserverData);
            return observerData;
        }

        [HttpPost]
        public long CreateNewReport(VReportInfo data)
        {
            return ReportBusiness.CreateNewReport(data.ID, data.IsObserveInfo, data.AutoImport);
        }

        [HttpPost]
        public void DelTrial(VTrial trial)
        {
            TrialBusiness.DelTrial(trial.ID);
        }

        public void DelTrialSite(VTrialSite trialSite)
        {
            TrialBusiness.DelTrialSite(trialSite.ID);
        }

    }
}
